package edu.ucsb.cs176b.android;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import com.google.android.c2dm.C2DMessaging;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class TreasureHunt extends Activity {
	
	String username;
	String host;
	String token;
	String regID;
	boolean regSuccess = true;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);

        Button regButton = (Button)findViewById(R.id.start_button);
        regButton.setOnClickListener(new OnClickListener() {		
        	public void onClick(View v) {
        		
        		// Parses the user input
        		EditText eUsername = (EditText)findViewById(R.id.username);
        		username = String.valueOf(eUsername.getText().toString());
        		username = username.replaceAll(" ", "");
        		System.out.println("username is " + username);
        		EditText servername = (EditText)findViewById(R.id.servername);
        		host = String.valueOf(servername.getText().toString());


        		new Thread(new Runnable() {
					
					@Override
					public void run() {
						login();	
					}
				}).start();	
        	}
        	
    	});
        

    }
    
    private void login(){

    	boolean registered = false;
		DBUtil dbUtil = new DBUtil(getApplicationContext());
		ArrayList<String> users = dbUtil.getUsers();
		for(int i = 0; i < users.size(); i++){
			String[] tokenstring = users.get(i).split(",");
			if(tokenstring[0].equalsIgnoreCase(username) && tokenstring[2].equalsIgnoreCase(host)){
				registered = true;
				System.out.println("Found match user " + username + "on host " + host);
				token = tokenstring[1];
				System.out.println("Token " + token);
			}
		}

		// Register user if not found in database
		if(!registered){
			// Gets new registration ID since the server requires that this is unique for the user
	        Intent registrationIntent = new Intent("com.google.android.c2dm.intent.REGISTER");
			registrationIntent.putExtra("app", PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent(), 0)); // boilerplate
			registrationIntent.putExtra("sender", "ucsb.cs.176b@gmail.com");
			startService(registrationIntent);
			
			
			// Waits until regID is received from Google before registerering a new user
			while(regID == null) {
				regID = C2DMessaging.getRegistrationId(getApplicationContext());
			}

      		System.out.println(regID);
    		String regURL = "http://"+host+"/register?name="+username+"&&registration_id="+regID+"&&phonetype=android";

    		String resString = NetworkUtil.getSringFromUrl(regURL);
			try {
				JSONObject jsonRes = new JSONObject(resString);
				JSONObject status = jsonRes.getJSONObject("status");
				
				if(status.getInt("code") == 0 || status.getInt("code") == 1 ) {
					System.out.println("in code 0 or 1");
					regSuccess = true;
					JSONObject response = jsonRes.getJSONObject("response");
					token = response.getString("token");
					dbUtil.addUser(username, token, host);
				}
				
				else if(status.getInt("code") == 1 ) {
					System.out.println("in 1");
					regSuccess = true;
					JSONObject response = jsonRes.getJSONObject("response");
					token = response.getString("token");
					dbUtil.addUser(username, token, host);
					String updateReg = NetworkUtil.getSringFromUrl("http://"+host+"/update_reg_id?token="+token+"&&registration_id="+regID);
					System.out.println(updateReg);
				}

				
				else if(status.getInt("code") == 90) {
					regSuccess = false;
					runOnUiThread(new Runnable() {
						public void run() {
							TextView t=(TextView)findViewById(R.id.status); 
					        t.setText("Invalid / Not unique registration ID");
						}
					});
				}
				
				else {
					regSuccess = false;
					runOnUiThread(new Runnable() {
						public void run() {
							TextView t=(TextView)findViewById(R.id.status); 
					        t.setText("Invalid parameters");
						}
					});
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
		}

		//Toast.makeText(getApplicationContext(), "token er " + token, Toast.LENGTH_LONG).show();
		// Sends user to MainMenu
		if(regSuccess) {
			Intent myIntent = new Intent(getApplicationContext(), MainMenu.class);
			myIntent.putExtra("username", username);
			myIntent.putExtra("token", token);
			myIntent.putExtra("host", host);
	        startActivity(myIntent);
		}
    }
}